
package com.jf.cloud.discount.feign;

import com.google.common.collect.Lists;
import com.jf.cloud.api.combo.feign.ComboFeignClient;
import com.jf.cloud.api.combo.feign.ComboSpuFeignClient;
import com.jf.cloud.api.combo.feign.ComboSpuSkuFeignClient;
import com.jf.cloud.api.combo.vo.ComboSkuVo;
import com.jf.cloud.api.discount.constant.DiscountRule;
import com.jf.cloud.api.discount.feign.DiscountFeignClient;
import com.jf.cloud.api.discount.vo.DiscountSumVO;
import com.jf.cloud.api.product.feign.GiveawayFeignClient;
import com.jf.cloud.api.product.feign.SkuFeignClient;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.order.constant.ShopCartItemDiscountType;
import com.jf.cloud.common.order.vo.*;
import com.jf.cloud.common.product.constant.ShopCartSpuActivityType;
import com.jf.cloud.common.product.vo.ComboSpuVO;
import com.jf.cloud.common.product.vo.ComboVO;
import com.jf.cloud.common.product.vo.SkuVO;
import com.jf.cloud.common.product.vo.SpuDiscountAppVO;
import com.jf.cloud.common.product.vo.search.SpuDiscountItemAppVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.util.Arith;
import com.jf.cloud.common.util.BooleanUtil;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.discount.manager.DiscountManager;
import com.jf.cloud.discount.service.DiscountService;
import com.jf.cloud.discount.vo.DiscountVO;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Hidden;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zz
 * @date 2020/12/14
 */
@RestController
@Hidden
public class DiscountFeignController implements DiscountFeignClient {

    @Autowired
    private DiscountManager discountManager;
    @Autowired
    private DiscountService discountService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private GiveawayFeignClient giveawayFeignClient;
    @Autowired
    private SkuFeignClient skuFeignClient;
    @Autowired
    private ComboSpuSkuFeignClient comboSpuSkuFeignClient;
    @Autowired
    private ComboSpuFeignClient comboSpuFeignClient;
    @Autowired
    private ComboFeignClient comboFeignClient;

    public static final Logger log = LoggerFactory.getLogger(DiscountFeignController.class);

    @Override
    public ServerResponseEntity<List<ShopCartVO>> calculateDiscountAndMakeUpShopCart(List<ShopCartVO> shopCarts) {

        List<ShopCartVO> newShopCart = new ArrayList<>();
        for (ShopCartVO shopCart : shopCarts) {
            newShopCart.add(reBuildShopCart(shopCart,shopCart.getShopCartItemDiscounts().get(0).getShopCartItems()));
        }

        return ServerResponseEntity.success(newShopCart);
    }

    @Override
    public ServerResponseEntity<ShopCartWithAmountVO> calculateDiscountAndMakeUpShopCartAndAmount(ShopCartWithAmountVO shopCartWithAmountVO) {
        List<ShopCartVO> shopCarts = shopCartWithAmountVO.getShopCarts();

        ServerResponseEntity<List<ShopCartVO>> calculateDiscountAndMakeUpShopCartResponse = calculateDiscountAndMakeUpShopCart(shopCarts);
        if (!calculateDiscountAndMakeUpShopCartResponse.isSuccess()) {
            return ServerResponseEntity.transform(calculateDiscountAndMakeUpShopCartResponse);
        }

        shopCarts = calculateDiscountAndMakeUpShopCartResponse.getData();

        long total = 0L;
        int count = 0;
        long reduce = 0L;
        long totalTransfee = 0L;
        long totalFreeTransfee = 0L;
        ShopCartWithAmountVO shopCartWithAmount = new ShopCartWithAmountVO();
        for (ShopCartVO shopCart : shopCarts) {
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();

            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                ChooseDiscountItemVO chooseDiscountItemVO = shopCartItemDiscount.getChooseDiscountItem();
                if(Objects.nonNull(chooseDiscountItemVO)) {
                    Long needPiece = chooseDiscountItemVO.getNeedAmount();
                    // 当规则为满件打折时 9.5折就是95、9.5元就是950，此时数据库存的是件数*100，还需除以100进行判断
                    if (Objects.equals(DiscountRule.P2D.value(), chooseDiscountItemVO.getDiscountRule())){
                        needPiece = PriceUtil.toDecimalPrice(needPiece).longValue();
                    }

                    // 如果满足优惠活动
                    if (Objects.equals(DiscountRule.M2M.value(), chooseDiscountItemVO.getDiscountRule()) && chooseDiscountItemVO.getNeedAmount() <= chooseDiscountItemVO.getProdsPrice()) {
                        //满钱减钱
                        reduce += chooseDiscountItemVO.getReduceAmount();
                    } else if (Objects.equals(DiscountRule.P2D.value(), chooseDiscountItemVO.getDiscountRule()) && needPiece <= chooseDiscountItemVO.getCount()) {
                        //满件打折
                        reduce += chooseDiscountItemVO.getReduceAmount();
                    }
                }

                for (ShopCartItemVO shopCartItem : shopCartItems) {
                    if (!BooleanUtil.isTrue(shopCartItem.getIsChecked())) {
                        continue;
                    }
                    count += shopCartItem.getCount();
                    total += shopCartItem.getTotalAmount();
                    if (Objects.nonNull(shopCartItem.getComboAmount())){
                        //如果是套餐商品需要减去套餐优惠金额
                        reduce += shopCartItem.getComboAmount();
                    }
                    // 前端页面套餐商品小计显示（套餐商品计算套餐价）
                    if (Objects.nonNull(shopCartItem.getComboId()) && shopCartItem.getComboId() > 0) {
                        log.info("套餐商品重新计算总金额");
                        Double totalAmount = Arith.mul(shopCartItem.getSkuPriceFee(), shopCartItem.getCount());
                        shopCartItem.setTotalAmount(totalAmount.longValue());
                    }
                }
            }

            Map<Long, ShopTransFeeVO> shopIdWithShopTransFee = null;
            if(Objects.nonNull(shopCartWithAmountVO.getUserDeliveryInfo())) {
                shopIdWithShopTransFee = shopCartWithAmountVO.getUserDeliveryInfo().getShopIdWithShopTransFee();
            }
            // 要计算运费
            if (shopIdWithShopTransFee != null && shopIdWithShopTransFee.containsKey(shopCart.getShopId())) {
                ShopTransFeeVO shopTransFeeVO = shopIdWithShopTransFee.get(shopCart.getShopId());

                // 店铺的实付 = 购物车实付 + 运费
                shopCart.setActualTotal(shopCart.getActualTotal() + shopTransFeeVO.getTransfee());
                // 店铺免运费金额
                shopCart.setFreeTransfee(shopTransFeeVO.getFreeTransfee());
                //店铺优惠金额 = 优惠金额  + 减免运费
                shopCart.setShopReduce(shopCart.getShopReduce() + shopTransFeeVO.getFreeTransfee());

                // 运费
                shopCart.setTransfee(shopTransFeeVO.getTransfee());
            } else {
                shopCart.setFreeTransfee(0L);
                shopCart.setTransfee(0L);
            }
            totalFreeTransfee += shopCart.getFreeTransfee();
            totalTransfee += shopCart.getTransfee();
        }

        shopCartWithAmount.setCount(count);
        shopCartWithAmount.setTotalMoney(total);
        shopCartWithAmount.setSubtractMoney(reduce);
        shopCartWithAmount.setFinalMoney(total + totalTransfee - reduce);
        shopCartWithAmount.setFreeTransfee(totalFreeTransfee);
        shopCartWithAmount.setFreightAmount(totalTransfee);
        shopCartWithAmount.setShopCarts(shopCarts);


        return ServerResponseEntity.success(shopCartWithAmount);
    }

    @Override
    public ServerResponseEntity<List<SpuDiscountAppVO>> spuDiscountList(Long shopId, Long spuId) {
        List<DiscountVO> discountList = discountService.spuDiscountList(shopId, spuId);
        List<SpuDiscountAppVO> spuDiscountList = new ArrayList<>();
        for (DiscountVO discountVO : discountList) {
            SpuDiscountAppVO spuDiscount = new SpuDiscountAppVO();
            spuDiscount.setDiscountId(discountVO.getDiscountId());
            spuDiscount.setDiscountName(discountVO.getDiscountName());
            spuDiscount.setDiscountRule(discountVO.getDiscountRule());
            spuDiscount.setDiscountType(discountVO.getDiscountType());
            spuDiscount.setMaxReduceAmount(discountVO.getMaxReduceAmount());
            spuDiscount.setDiscountItemList(mapperFacade.mapAsList(discountVO.getDiscountItemList(), SpuDiscountItemAppVO.class));
            spuDiscountList.add(spuDiscount);
        }
        return ServerResponseEntity.success(spuDiscountList);
    }

    @Override
    public ServerResponseEntity<Void> handleSpuOffline(List<Long> spuIds, List<Long> shopIds) {
        discountService.handleSpuOffline(spuIds, shopIds);
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<Void> handleShopOffline(List<Long> shopIds) {
        discountService.handleShopOffline(shopIds);
        return ServerResponseEntity.success();
    }


    private ShopCartVO reBuildShopCart(ShopCartVO shopCart, List<ShopCartItemVO> shopCartItems) {
        // 购物车项顺序
        List<Long> cartOrderArr = shopCartItems.stream().map(ShopCartItemVO::getCartItemId).collect(Collectors.toList());
        // 订单项金额从小到大排序
        shopCartItems = shopCartItems.stream().sorted(Comparator.comparingDouble(ShopCartItemVO::getActualTotal)).collect(Collectors.toList());

        shopCart.setShopReduce(0L);
        shopCart.setDiscountReduce(0L);
        // 1.获取总的优惠金额
        // 2.将商品活动进行保存
        DiscountSumVO discountSum = discountManager.calculateDiscount(shopCart.getShopId(), shopCartItems);

        List<ShopCartItemDiscountVO> shopCartItemDiscountVOList = Lists.newArrayList();

        // 对数据经行组装
        // 通过活动项id划分,获取有活动的商品项
        //如果是套餐商品不划分
        for (ShopCartItemVO shopCartItem : shopCartItems) {
            if (Objects.nonNull(shopCartItem.getComboId()) && shopCartItem.getComboId() > 0){
                shopCartItem.setDiscountId(0L);
            }
        }
        Map<Long, List<ShopCartItemVO>> hasDiscountShopCartItemMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemVO::getDiscountId));

        long reduce = 0L;
        long total = 0L;
        long actualTotal = 0L;
        int totalCount = 0;
        for (Long discountId : hasDiscountShopCartItemMap.keySet()) {
            // 获取该列表
            List<ShopCartItemVO> shopCartItemvos = hasDiscountShopCartItemMap.get(discountId);
            ChooseDiscountItemVO chooseDiscountItemVO = discountManager.getChooseDiscountItemVO(discountSum,discountId);


            long discountAmount = 0L;


            // 分摊优惠大于订单项金额的数量
            long shareReduceBiggerThenShopItemAmount = 0;
            // 计算分摊优惠金额
            for (int index = 0; index < shopCartItemvos.size(); index++) {

                ShopCartItemVO shopCartItem = shopCartItemvos.get(index);
                total += shopCartItem.getTotalAmount();
                actualTotal += shopCartItem.getActualTotal();
                totalCount += shopCartItem.getCount();

                if (!BooleanUtil.isTrue(shopCartItem.getIsChecked())) {
                    continue;
                }

                long shareReduce = 0L;
                if (Objects.isNull(chooseDiscountItemVO)){
                    shopCartItem.setShareReduce(shopCartItem.getShareReduce() + shareReduce);
                    shopCartItem.setActualTotal(shopCartItem.getActualTotal() - shareReduce);
                    continue;
                }

                if(index + 1 == shopCartItems.size()){
                    shareReduce = chooseDiscountItemVO.getReduceAmount() - discountAmount;
                    // 如果分到最后一项的钱太多了，比订单项目金额都要多，订单项的分摊金额就当作订单项金额咯
                    if (shareReduce > shopCartItem.getActualTotal()) {
                        shareReduceBiggerThenShopItemAmount = shareReduce - shopCartItem.getActualTotal();
                        shareReduce = shopCartItem.getActualTotal();
                        // 给得太多了，减少一点，以免变成负数
                        chooseDiscountItemVO.setReduceAmount(chooseDiscountItemVO.getReduceAmount() - shareReduceBiggerThenShopItemAmount);
                    }
                }else {
                    // 分摊金额 = 该优惠活动优惠金额 * (商品金额 / 参与该活动的商品总金额)
                    shareReduce = PriceUtil.divideByBankerRounding(chooseDiscountItemVO.getReduceAmount() * shopCartItem.getActualTotal(), chooseDiscountItemVO.getProdsPrice());
                }
                // 第一个优惠就是满减
                shopCartItem.setShareReduce(shopCartItem.getShareReduce() + shareReduce);
                shopCartItem.setDiscountAmount(shareReduce);
                shopCartItem.setActualTotal(shopCartItem.getActualTotal() - shareReduce);
                discountAmount += shareReduce;

            }

            // 不要把这行放到上面，因为上面会重新计算该值
            if (chooseDiscountItemVO != null) {
                reduce +=  chooseDiscountItemVO.getReduceAmount();
            }
            ShopCartItemDiscountVO shopCartItemDiscountVO = new ShopCartItemDiscountVO();
            // 把购物车项的商品顺序还原
            shopCartItemvos.sort(Comparator.comparingInt(prev -> cartOrderArr.indexOf(prev.getCartItemId())));

            shopCartItemDiscountVO.setShopCartItems(shopCartItemvos);
            shopCartItemDiscountVO.setChooseDiscountItem(chooseDiscountItemVO);
            shopCartItemDiscountVOList.add(shopCartItemDiscountVO);
        }

        // 倒序排序，将拥有优惠活动的商品放到最上面
        Collections.reverse(shopCartItemDiscountVOList);

        shopCart.setShopCartItemDiscounts(shopCartItemDiscountVOList);

        //获取套餐商品
        buildComboShopCartBefore(shopCart);
        //套餐商品放到最前面
        cartArrange(shopCart);
        //获取套餐优惠价格
        Long discounts = combDiscounts(shopCart);
        shopCart.setTotal(total);
        shopCart.setTotalCount(totalCount);
        shopCart.setActualTotal(actualTotal - reduce - discounts);
        shopCart.setDiscountReduce(reduce);
        // 最开始的店铺满减
        shopCart.setShopReduce(reduce);
        //获取赠品
        shopCart = giveawayFeignClient.buildGiveaway(shopCart).getData();
//        giveawayFeignClient.buildGiveaway(shopCartItems);
        shopCart.setShopReduce(reduce + discounts);
        shopCart.setShopComboAmount(discounts);


        return shopCart;
    }

    /**
     * 获取套餐优惠金额
     * @param shopCart
     * @return
     */
    private Long combDiscounts(ShopCartVO shopCart){
        Long discountsSum = 0L;
        List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
        for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
            if (Objects.equals(shopCartItemDiscount.getType(), ShopCartSpuActivityType.COMBO.value())){
                discountsSum += shopCartItemDiscount.getChooseComboItemVo().getPreferentialAmount();
            }
        }
        return discountsSum;
    }

    /**
     * 取出购物车中套餐商品
     * @param shopCart
     */
    private void buildComboShopCartBefore(ShopCartVO shopCart){
        //取出套餐商品
        List<ShopCartItemDiscountVO> itemDiscounts = shopCart.getShopCartItemDiscounts();
        ListIterator<ShopCartItemDiscountVO> shopCartItemDiscountListIterator = itemDiscounts.listIterator();
        while (shopCartItemDiscountListIterator.hasNext()){
            List<ShopCartItemVO> items = shopCartItemDiscountListIterator.next().getShopCartItems();
            Iterator<ShopCartItemVO> itemIterator = items.iterator();
            List<ShopCartItemVO> shopCartComboItems = new ArrayList<>();
            while (itemIterator.hasNext()){
                ShopCartItemVO cartItemVO = itemIterator.next();
                if (Objects.nonNull(cartItemVO.getComboId()) && cartItemVO.getComboId() > 0){
                    shopCartComboItems.add(cartItemVO);
                    itemIterator.remove();
                }
            }
            if (shopCartComboItems.size() == 0){
                continue;
            }
            List<ShopCartItemDiscountVO> comboShopCartItemDiscountVOList = buildComboShopCart(shopCartComboItems);
            for (ShopCartItemDiscountVO shopCartItemDiscountVO : comboShopCartItemDiscountVOList) {
                shopCartItemDiscountListIterator.add(shopCartItemDiscountVO);
            }
        }
    }
    /**
     * 将套餐商品放到最前面
     * @param shopCartVO
     */
    private void cartArrange(ShopCartVO shopCartVO){
        List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartVO.getShopCartItemDiscounts();
        ListIterator<ShopCartItemDiscountVO> shopCartItemDiscountListIterator = shopCartItemDiscounts.listIterator();
        List<ShopCartItemDiscountVO> comboCart = new ArrayList<>();
        List<ShopCartItemDiscountVO> noComboCart = new ArrayList<>();
        while (shopCartItemDiscountListIterator.hasNext()){
            ShopCartItemDiscountVO cartItemDiscountVO = shopCartItemDiscountListIterator.next();
            if (cartItemDiscountVO.getShopCartItems().size() == 0){
                shopCartItemDiscountListIterator.remove();
                continue;
            }
            if (Objects.isNull(cartItemDiscountVO.getType())){
                noComboCart.add(cartItemDiscountVO);
            }else {
                comboCart.add(cartItemDiscountVO);
            }
        }
        comboCart.addAll(noComboCart);
        shopCartVO.setShopCartItemDiscounts(comboCart);
    }

    /**
     * 组装套餐信息
     * @param shopCartComboItems
     * @return
     */
    private List<ShopCartItemDiscountVO> buildComboShopCart(List<ShopCartItemVO> shopCartComboItems){
        List<ShopCartItemDiscountVO> shopCartItemDiscountVOList = new ArrayList<>();
        //获取购物车商品套餐信息
        Set<Long> comboIdList = shopCartComboItems.stream().map(e -> e.getComboId()).collect(Collectors.toSet());
        //skuId集合
        List<Long> skuIdList = shopCartComboItems.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
        //根据套餐id分组
        Map<Long, List<ShopCartItemVO>> shopCartGroupByComboId = groupByComboId(shopCartComboItems);
        //获取套餐信息
        List<ComboSkuVo> comboList = comboSpuSkuFeignClient.comboVoListComboAndSkuList(comboIdList, skuIdList).getData();
        Map<Long, List<ComboSkuVo>> comboSkuVoMap = comboList.stream().collect(Collectors.groupingBy(ComboSkuVo::getSkuId));
        // 获取套餐信息，进行缓存
        List<ComboVO> comboByComboIdList = comboFeignClient.getComboByComboIdList(new ArrayList<>(comboIdList)).getData();
        comboByComboIdList.forEach(comboVO -> {
            RedisUtil.set(CacheNames.ORDER_COMBO_STATUS + comboVO.getComboId(), comboVO.getStatus(), 3600);
            RedisUtil.set(CacheNames.ORDER_COMBO_EXPIRATION_TIME + comboVO.getComboId(), comboVO.getEndTime().getTime(), 3600);
        });
        Map<Long, String> comboName = comboNameGroupByComboId(comboList);
        for (Long comboId : comboIdList) {
            //每个套餐的商品信息
            List<ShopCartItemVO> shopCartItemList = shopCartGroupByComboId.get(comboId);
            for (ShopCartItemVO shopCartItemVO : shopCartItemList) {
                List<ComboSkuVo> comboSkuVos = comboSkuVoMap.get(shopCartItemVO.getSkuId());
                if (Objects.isNull(comboSkuVos) || comboSkuVos.size() == 0){
                    continue;
                }
                ComboSkuVo comboSkuVo = comboSkuVos.get(0);
                //设置商品套餐价格
                shopCartItemVO.setMatchingPrice(comboSkuVo.getMatchingPrice());
                shopCartItemVO.setPriceFee(comboSkuVo.getMatchingPrice());
                shopCartItemVO.setSkuPriceFee(comboSkuVo.getMatchingPrice());
            }
            ChooseComboItemVo chooseComboItemVo = new ChooseComboItemVo();
            chooseComboItemVo.setComboId(comboId);
            chooseComboItemVo.setName(comboName.get(comboId));
            ShopCartItemDiscountVO shopCartItemDiscountVO = new ShopCartItemDiscountVO();
            shopCartItemDiscountVO.setChooseComboItemVo(chooseComboItemVo);
            shopCartItemDiscountVO.setType(ShopCartItemDiscountType.COMBO.value());
            shopCartItemDiscountVO.setShopCartItems(shopCartItemList);
            shopCartItemDiscountVOList.add(shopCartItemDiscountVO);
        }

        //套餐主商品放到套餐商品首位
        for (ShopCartItemDiscountVO cartItemDiscountVO : shopCartItemDiscountVOList) {
            List<ShopCartItemVO> shopCartItems = cartItemDiscountVO.getShopCartItems();
            for (int i = 0; i < shopCartItems.size(); i++) {
                if (Objects.isNull(shopCartItems.get(i).getParentCartItemId())){
                    //套餐主商品
                    shopCartItems.get(i).setIsMainProd(1);
                    Collections.swap(shopCartItems,i,0);
                }else {
                    //套餐搭配商品
                    shopCartItems.get(i).setIsMainProd(-1);
                }
            }
        }
        shopCartItemDiscountVOList = shopCartItemDiscountVOList(shopCartItemDiscountVOList);
        //根据套餐加入时间排序(先加入的放后面，后加入的放前面)
        shopCartItemDiscountVOList = shopCartItemDiscountVOList.stream().sorted(Comparator.comparing(ShopCartItemDiscountVO::getComboJoinTime).reversed()).collect(Collectors.toList());
        return shopCartItemDiscountVOList;
    }

    /**
     * 相同套餐商品不同sku组成不同的套餐信息
     * @param discountVOList
     * @return
     */
    private List<ShopCartItemDiscountVO> shopCartItemDiscountVOList(List<ShopCartItemDiscountVO> discountVOList){
        List<ShopCartItemDiscountVO> shopCartItemDiscountVOList = new ArrayList<>();
        for (ShopCartItemDiscountVO discountVO : discountVOList) {
            //套餐
            Map<Long,List<ShopCartItemVO>> shopCartItemMap = new HashMap<>();
            List<ShopCartItemVO> shopCartItems = discountVO.getShopCartItems();
            //skuId集合
            List<Long> skuIdList = shopCartItems.stream().map(e -> e.getSkuId()).collect(Collectors.toList());
            //获取套餐中sku原售价
            List<SkuVO> skuList  = skuFeignClient.getByIds(skuIdList).getData();
            //套餐商品信息
            List<ComboSpuVO> comboSpuVOList = comboSpuFeignClient.comboSpuByComboId(discountVO.getChooseComboItemVo().getComboId()).getData();
            Map<Long, List<ComboSpuVO>> comboSpuMap = comboSpuVOList.stream().collect(Collectors.groupingBy(ComboSpuVO::getSpuId));
            //获取套餐信息
            Map<Long, Long> skuPriceFeeMap = skuList .stream().collect(Collectors.toMap(SkuVO::getSkuId, SkuVO::getPriceFee));
            for (ShopCartItemVO shopCartItem : shopCartItems){
                //如果是主商品，则往map中put新的值
                if (Objects.isNull(shopCartItem.getParentCartItemId())){
                    List<ShopCartItemVO> shopCartItemList = new ArrayList<>();
                    shopCartItemList.add(shopCartItem);
                    shopCartItemMap.put(shopCartItem.getCartItemId(),shopCartItemList);
                }
            }
            for (ShopCartItemVO shopCartItem : shopCartItems) {
                //主商品跳过执行
                if (Objects.isNull(shopCartItem.getParentCartItemId())){
                    continue;
                }
                //根据搭配商品中的主购物车id获取map中数据
                List<ShopCartItemVO> shopCartItemList = shopCartItemMap.get(shopCartItem.getParentCartItemId());
                if (Objects.isNull(shopCartItemList)){
                    continue;
                }
                //将搭配商品数据追加到map value中
                shopCartItemList.add(shopCartItem);
                shopCartItemMap.put(shopCartItem.getParentCartItemId(),shopCartItemList);
            }

            for (List<ShopCartItemVO> value : shopCartItemMap.values()) {
                ShopCartItemDiscountVO shopCartItemDiscountVO = new ShopCartItemDiscountVO();
                shopCartItemDiscountVO.setShopCartItems(value);
                shopCartItemDiscountVO.setType(ShopCartItemDiscountType.COMBO.value());
                //重新计算套餐价格
                Long comboTotalAmount = 0L;
                //套餐数量
                Integer count = 0;
                //套餐金额(套餐单价)
                Long comboAmount = 0L;
                //套餐优惠价格
                Long preferentialAmount = 0L;
                for (ShopCartItemVO shopCartItemVO : value) {
                    comboTotalAmount += shopCartItemVO.getMatchingPrice() * shopCartItemVO.getCount();
                    ComboSpuVO comboSpuVO = comboSpuMap.get(shopCartItemVO.getSpuId()).get(0);
                    int leastNum = comboSpuVO.getLeastNum();
                    if (Objects.isNull(shopCartItemVO.getParentCartItemId())){
                        //套餐主商品才会执行
                        //套餐数量 = 主商品加入购物车数量 / 主商品起搭数量
                        count = shopCartItemVO.getCount()/comboSpuVO.getLeastNum();
                    }
                    comboAmount += shopCartItemVO.getMatchingPrice() * leastNum;
                    //商品sku套餐价格
                    //sku原价
                    Long skuPriceFee = skuPriceFeeMap.get(shopCartItemVO.getSkuId()) *  shopCartItemVO.getCount();
                    //sku套餐价格
                    Long comboSkuPrice = shopCartItemVO.getMatchingPrice() *  shopCartItemVO.getCount();
                    //单个sku优惠金额
                    Long onePreferentialAmount = skuPriceFee - comboSkuPrice;
                    preferentialAmount = preferentialAmount + onePreferentialAmount;
                    shopCartItemVO.setComboAmount(onePreferentialAmount);
                    shopCartItemVO.setActualTotal(comboSkuPrice);
                }
                ChooseComboItemVo chooseComboItemVo = new ChooseComboItemVo();
                chooseComboItemVo.setComboId(discountVO.getChooseComboItemVo().getComboId());
                chooseComboItemVo.setName(discountVO.getChooseComboItemVo().getName());
                chooseComboItemVo.setComboCount(count);
                chooseComboItemVo.setComboTotalAmount(comboTotalAmount);
                chooseComboItemVo.setComboAmount(comboAmount);
                chooseComboItemVo.setPreferentialAmount(preferentialAmount);
                shopCartItemDiscountVO.setChooseComboItemVo(chooseComboItemVo);
                shopCartItemDiscountVO.setComboJoinTime(value.get(0).getCreateTime());
                shopCartItemDiscountVOList.add(shopCartItemDiscountVO);
            }
        }
        return shopCartItemDiscountVOList;
    }
    /**
     * 根据套餐id分组
     * @param shopCartComboItems
     * @return
     * @throws Exception
     */
    private Map<Long, List<ShopCartItemVO>> groupByComboId(List<ShopCartItemVO> shopCartComboItems){
        Map<Long, List<ShopCartItemVO>> resultMap = new HashMap<>();
        for(ShopCartItemVO shopCartItemVO : shopCartComboItems){
            if(resultMap.containsKey(shopCartItemVO.getComboId())){
                //存在相同的key，把值加入到key
                resultMap.get(shopCartItemVO.getComboId()).add(shopCartItemVO);
            }else{//map中不存在，新建key，用来存放数据
                List<ShopCartItemVO> tmpList = new ArrayList<>();
                tmpList.add(shopCartItemVO);
                resultMap.put(shopCartItemVO.getComboId(), tmpList);
            }

        }
    return resultMap;
    }

    /**
     * 根据套餐id分组value为套餐名称
     * @param comboList
     * @return
     * @throws Exception
     */
    private Map<Long, String> comboNameGroupByComboId(List<ComboSkuVo> comboList){
        Map<Long, String> resultMap = new HashMap<>();
        for(ComboSkuVo comboSkuVo : comboList){
            if(resultMap.containsKey(comboSkuVo.getComboId())){
                //存在相同的key，则跳出此次循环
                continue;
            }else{
                //map中不存在，新建key，用来存放数据
                resultMap.put(comboSkuVo.getComboId(), comboSkuVo.getName());
            }
        }
        return resultMap;
    }

}
